require.config({
    paths: {
        'html2canvas': "../addons/fastflow/plugins/html2canvas/html2canvas.min",
        'compression': "../addons/fastflow/plugins/compression/compression",
        'bootstrapPaginator': "../addons/fastflow/plugins/bootstrap/bootstrap-paginator.min"
    },
});
define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template', 'html2canvas', 'compression', 'fastflow-base', 'bootstrapPaginator'], function ($, undefined, Backend, Table, Form, Template, Html2canvas, Compression, FastflowBase) {
    var Controller = {
        initiate: function () {
            Form.api.bindevent($("form[role=form]"));
            $('button[type="submit"]').click(function (e) {
                e.stopPropagation();
                e.preventDefault();
                var loadIndex = layer.load();
                var ebillIframe = $('#ebill-iframe')[0].contentWindow.document;
                var ebillContent = $(ebillIframe).find('#ebill-content');
                var ebillImage = $(ebillContent).css('background-image');
                ebillImage = ebillImage.match(/url\("(\S*)"\)/)[1];
                //处理base64字符串，将特殊符号%、&、+等进行转义
                ebillImage = ebillImage
                    .replace(/%/g, "%25")
                    .replace(/&/g, "%26")
                    .replace(/\+/g, "%2B");
                var ebillWidth = ebillContent.css('width').replace('px', '');
                var ebillHeight = ebillContent.css('height').replace('px', '');
                var firstsectionwidth = ebillContent.data('fswidth').replace('px', '');
                var firstsectionheight = ebillContent.data('fsheight').replace('px', '');
                Compression.Clipping(ebillImage, firstsectionwidth, firstsectionheight, 1, function (result) {
                    //处理base64字符串，将特殊符号%、&、+等进行转义
                    result = result
                        .replace(/%/g, "%25")
                        .replace(/&/g, "%26")
                        .replace(/\+/g, "%2B");
                    $.ajax({
                        type: "post",
                        url: location.href,
                        data: $('#signature-form').serialize() + '&ebill=' + ebillImage + '&ebill_width=' + ebillWidth + '&ebill_height=' + ebillHeight + '&thumbnail=' + result + '&firstsectionwidth=' + firstsectionwidth + '&firstsectionheight=' + firstsectionheight,
                        success: function (data) {
                            if (data['code'] === 1) {
                                parent.Toastr.success(data['msg']);
                                Layer.close(loadIndex);
                                let index = parent.Layer.getFrameIndex(window.name);
                                parent.Layer.close(index);
                                parent.$('.btn-refresh', parent.document).trigger('click');
                            } else if (data['code'] === 0) {
                                Layer.close(loadIndex);
                                Toastr.error(data['msg']);
                            }
                        }
                    });
                });
                return false;
            });
        },
        canstamp: function () {
            var action = 'canstamp';
            var bill = $('.bill-list li:first-child').data('bill');

            Controller.api.common.refresh(action, bill, 'stamp', '签章', false);

            $('.bill-item').click(function (e) {
                $(this).siblings().removeClass('active');
                $(this).addClass('active');
                Controller.api.common.refresh(action, $(this).data('bill'), 'stamp', '签章', true);
            });
            $('#refresh').click(function () {
                Controller.api.common.refresh(action, $('.bill-item.active').data('bill'), 'stamp', '签章', true);
                FastflowBase.api.renderbadge();
            });
        },
        stamped: function () {
            var action = 'stamped';
            var bill = $('.bill-list li:first-child').data('bill');

            Controller.api.common.refresh(action, bill, 'preview', '签章预览');

            $('.bill-item').click(function (e) {
                $(this).siblings().removeClass('active');
                $(this).addClass('active');
                Controller.api.common.refresh(action, $(this).data('bill'), 'preview', '签章预览');
            });
            $('#refresh').click(function () {
                Controller.api.common.refresh(action, $('.bill-item.active').data('bill'), 'preview', '签章预览');
            });
        },
        initiated: function () {
            var action = 'initiated';
            var bill = $('.bill-list li:first-child').data('bill');

            Controller.api.common.refresh(action, bill, 'preview', '签章预览');

            $('.bill-item').click(function (e) {
                $(this).siblings().removeClass('active');
                $(this).addClass('active');
                Controller.api.common.refresh(action, $(this).data('bill'), 'preview', '签章预览');
            });
            $('#refresh').click(function () {
                Controller.api.common.refresh(action, $('.bill-item.active').data('bill'), 'preview', '签章预览');
            });
        },
        stamp: function () {
            var stamped = [];
            containerWidth = $('#ebill').css('width').replace('px', '');
            contentWidth = $('#ebill-content').css('width').replace('px', '');
            $('#ebill').animate({scrollLeft: (contentWidth - containerWidth + 12) / 2}, 0);
            $('.card', '.stamp-list').click(function () {
                var stampWidth = 110;
                var stampHeight = 110;
                var stamp = $('#stamp');
                var ebill = $('#ebill');
                stamp
                    .css('top', ebill.height() / 2.5 + ebill.scrollTop())
                    .css('left', ebill.width() / 2.5 + ebill.scrollLeft())
                $('.stamp-content', stamp)
                    .css('width', stampWidth)
                    .css('height', stampHeight)
                    .css('background-image', $('.stamp-image', this).css('background-image'))
                    .data('id', $(this).data('id'));
                stamp.removeClass('hidden');
                //绑定移动事件
            });
            Controller.api.stamp.bindStampEvent(stamped);
            Controller.api.stamp.bindUndoEvent(stamped);
            Controller.api.stamp.bindFooterEvent(stamped);
        },
        preview: function () {
            containerWidth = $('#ebill').css('width').replace('px', '');
            contentWidth = $('#ebill-content').css('width').replace('px', '');
            $('#ebill').animate({scrollLeft: (contentWidth - containerWidth + 12) / 2}, 0);
            Controller.api.preview.bindPrintEvent();
        },
        check: function(){
            Form.api.bindevent($("form[role=form]"));
            Controller.api.check.bindEvent();
        },

        api: {
            common: {
                refresh: function (action, bill, dialogController, title, refreshBill = false) {
                    var index = layer.load();
                    if (refreshBill) {
                        $.ajax({
                            type: "get",
                            url: 'fastflow/signature/getBillCanstampCount',
                            data: {bill: bill},
                            success: function (data) {
                                if (data['code'] == 1) {
                                    data['bills'].forEach(function (bill) {
                                        var li = $('li[data-bill="' + bill["bill_table"] + '"]');
                                        li.data('count', bill['canstampCount']);
                                        li.find('small').html(bill['canstampCount']);
                                        var badage = li.find('.canstamp-badge');
                                        if (bill['canstampCount'] > 0) {
                                            badage.removeClass('hidden');
                                        } else {
                                            badage.addClass('hidden');
                                        }
                                    });
                                    Controller.api.common.initPagination(action, dialogController, title, bill, $('.bill-item.active').data('count'));
                                    //$('#pagination').bootstrapPaginator("showFirst")不起作用，这里手动添加第一页数据
                                    Controller.api.common.addEbills(bill, 1, 20, action, dialogController, title);
                                } else if (data['code'] == 0) {
                                    Toastr.error(data['msg']);
                                }
                                layer.close(index);
                            },
                            error: function (e) {
                                layer.close(index);
                            }
                        });
                    } else {
                        Controller.api.common.initPagination(action, dialogController, title, bill, $('.bill-item.active').data('count'));
                        //$('#pagination').bootstrapPaginator("showFirst")不起作用，这里手动添加第一页数据
                        Controller.api.common.addEbills(bill, 1, 20, action, dialogController, title);
                    }
                    layer.close(index);
                },
                initPagination: function (action, dialogController, title, bill, count) {
                    count = count == 0 ? 1 : count;
                    var pageSize = 20;
                    $('#pagination').bootstrapPaginator({
                        currentPage: 1, //当前页
                        totalPages: Math.ceil(count / pageSize), //总页
                        size: "normal",
                        bootstrapMajorVersion: 3,
                        alignment: "right",
                        numberOfPages: 10,
                        itemTexts: function (type, page, current) {
                            switch (type) {
                                case "first":
                                    return "首页";
                                case "prev":
                                    return "上一页";
                                case "next":
                                    return "下一页";
                                case "last":
                                    return "末页";
                                case "page":
                                    return page;
                            }
                        }, onPageClicked: function (event, originalEvent, type, page) {
                            Controller.api.common.addEbills(bill, page, pageSize, action, dialogController, title);
                        }
                    });
                },
                addEbills: function (bill, page, pageSize, action, dialogController, title) {
                    $.ajax({
                        type: "post",
                        url: "fastflow/signature/getPageData",
                        data: {
                            "action": action,
                            "page": page,
                            "pageSize": pageSize,
                            "bill": bill,
                        },
                        success: function (data) {
                            $('.imgProd', '.ebill-list').unbind('click');
                            $('.btn-stamp').unbind('click');
                            var ebills = data['ebills'];
                            var html = Template('itemTpl', {list: ebills});
                            document.getElementById('contenedorCards').innerHTML = html;
                            ebills.length !== 0 ? $('.empty-hint').hide() : $('.empty-hint').show();
                            Controller.api.common.bindStampButtonEvent(action, dialogController, title);
                            Controller.api.common.bindEbillThumbnailEvent(action, dialogController, title);
                            Controller.api.common.bindRepealButtonEvent();
                        }
                    });

                },
                bindStampButtonEvent: function (action, dialogController, title) {
                    $('.btn-stamp').click(function (e) {
                        $(this).closest('.wrapper').find('.imgProd')[0].click();
                    });
                },
                bindEbillThumbnailEvent: function (action, dialogController, title) {
                    $('.imgProd').click(function () {
                        if (action == 'perview') {
                            $(this).data('area', ['60%', '90%']);
                        } else {
                            $(this).data('area', ['80%', '90%']);
                        }
                        Fast.api.open('fastflow/signature/' + dialogController + '?id=' + $(this).data('id'), title, $(this).data() || {});

                    });
                },
                bindRepealButtonEvent: function () {
                    $('.btn-repeal').click(function () {
                        var that = this;
                        var top = $(that).offset().top - $(window).scrollTop();
                        var left = $(that).offset().left - $(window).scrollLeft() - 160;
                        if (top + 154 > $(window).height()) {
                            top = top - 154;
                        }
                        if ($(window).width() < 480) {
                            top = left = undefined;
                        }
                        Layer.confirm(
                            __('确定撤销吗?'),
                            {
                                icon: 3,
                                title: __('Warning'),
                                offset: [top, left],
                                shadeClose: true,
                                btn: [__('OK'), __('Cancel')]
                            },
                            function (index) {
                                $.ajax({
                                    type: "post",
                                    url: "fastflow/signature/repeal",
                                    data: {id: $(that).data('id')},
                                    success: function (data) {
                                        if (data['code'] == 1) {
                                            Toastr.success('撤销成功');
                                            $('#refresh').trigger('click');
                                        } else if (data['code'] == 0) {
                                            Toastr.error(data['msg']);
                                        }
                                        layer.close(index);
                                    },
                                    error: function (e) {
                                        layer.close(index);
                                    }
                                });
                                Layer.close(index);
                            }
                        );
                    });
                }
            },
            canstamp: {},
            stamped: {},
            initiate: {},
            stamp: {
                bindStampEvent: function (stamped) {
                    var stamp = $('#stamp');
                    Controller.api.stamp.resizeable($('.stamp-content', stamp), 80, 80, 160, 160, true);
                    var range = {
                        minX: 0,
                        minY: 0,
                        maxX: $('#ebill-content').width() - stamp.width() + 8,
                        maxY: $('#ebill-content').height() - stamp.height() + 8
                    };
                    //绑定移动事件
                    stamp.on('mousedown', function (e) {
                        stamp.data('x', e.clientX);
                        stamp.data('y', e.clientY);
                        var position = stamp.position();
                        $(document).on('mousemove', function (e1) {
                            var x = e1.clientX - stamp.data('x') + position.left;
                            var y = e1.clientY - stamp.data('y') + position.top;
                            x = x < range.minX ? range.minX : x;
                            x = x > range.maxX ? range.maxX : x;
                            y = y < range.minY ? range.minY : y;
                            y = y > range.maxY ? range.maxY : y;
                            stamp.css({left: x, top: y});
                        }).on('mouseup', function () {
                            $(this).off('mousemove').off('mouseup');
                        });
                    });

                    $('.stamp-ok', stamp).click(function () {
                        var stampCopy = $('.stamp-content', stamp).clone();
                        stampCopy.data('id', $('.stamp-content', stamp).data('id'));
                        stampCopy.children().remove();
                        stampCopy.addClass('stamped');
                        stamp.before(stampCopy);
                        stampCopy.css('top', parseFloat(stamp.css('top')) + 1);
                        stampCopy.css('left', parseFloat(stamp.css('left')) + 1);
                        stamp.addClass('hidden').css('top', '200px').css('left', '40%');
                        stamped.push(stampCopy);
                        $('#undo').removeClass('disabled');
                        $('button[type="submit"]').removeAttr('disabled');
                    });
                    $('.stamp-cancel', stamp).click(function () {
                        stamp.addClass('hidden').css('top', '200px').css('left', '40%');
                    });

                    window.onresize = function () {
                        range.maxX = $('#ebill-content').width() - 102;
                        range.maxY = $('#ebill-content').height() - 102 + 30;
                    };
                },
                resizeable: function (element, minWidth, minHeight, maxWidth, maxHeight, fixedRatio = false) {
                    var handleBottomRight = $(document.createElement('div'));
                    handleBottomRight.addClass('resizeHandle-br');
                    element.append(handleBottomRight);
                    handleBottomRight.on('mousedown', function (event) {
                        var that = this;
                        var distanceX = event.clientX - $(that).position().left;
                        var distanceY = event.clientY - $(that).position().top;//同理
                        $(document).on('mousemove', function (e) {
                            var width = e.clientX - distanceX + $(that)[0].offsetWidth;
                            var height = e.clientY - distanceY + $(that)[0].offsetHeight;
                            width = width > maxWidth ? maxWidth : width < minWidth ? minWidth : width;
                            height = height > maxHeight ? maxHeight : height < minHeight ? minHeight : height;
                            if (fixedRatio) {
                                if (width > height) {
                                    height = width;
                                } else {
                                    width = height;
                                }
                            }
                            element.width(width).height(height);
                        });
                        $(document).on('mouseup', function (e) {
                            $(this).off('mousemove');
                            $(this).off('mouseup');
                        });
                        return false;
                    });
                },
                bindUndoEvent: function (stamped) {
                    $('#undo').click(function () {
                        if (stamped.length > 0) {
                            var lastStamp = stamped.pop();
                            lastStamp.remove();
                        }
                        if (stamped.length == 0) {
                            $(this).addClass('disabled');
                            $('button[type="submit"]').attr('disabled', 'disabled');
                        }
                    });

                },
                bindFooterEvent: function (stamped) {
                    $('button[type="submit"]').click(function () {
                        var index = layer.load();
                        $('#stamp').addClass('hidden');
                        var stampedData = [];
                        stamped.forEach(function (item) {
                            stampedData.push({"id": item.data('id'), "width": item.css('width'), "height": item.css('height'), "left": item.position().left, "top": item.position().top});
                        });
                        Controller.api.stamp.screenShot('ebill-content', function (canvas) {
                            if (canvas !== null) {
                                var canvasWidth = canvas.width;
                                var canvasHeight = canvas.height;
                                var data = canvas.toDataURL();

                                data = data
                                    .replace(/%/g, "%25")
                                    .replace(/&/g, "%26")
                                    .replace(/\+/g, "%2B");
                                var ebillImage = data;
                                //截取部分生成缩略图
                                Compression.Clipping(ebillImage, Config.thumb_width, Config.thumb_height, 1, function (thumbnail) {
                                    //处理base64字符串，将特殊符号%、&、+等进行转义
                                    thumbnail = thumbnail
                                        .replace(/%/g, "%25")
                                        .replace(/&/g, "%26")
                                        .replace(/\+/g, "%2B");
                                    $.ajax({
                                        type: "post",
                                        url: location.href,
                                        data: 'stampeddata=' + JSON.stringify(stampedData) + '&ebill=' + data + '&thumbnail=' + thumbnail,//此处需要以字符串形式提交，否则会与发起签章时提交的数据不一致，以数组提交会自动将所有特殊符号进行转义
                                        success: function (data) {
                                            if (data['code'] === 1) {
                                                parent.Toastr.success(data['msg']);
                                                let index = parent.Layer.getFrameIndex(window.name);
                                                parent.Layer.close(index);
                                                parent.$('#refresh', parent.document).trigger('click');
                                            } else if (data['code'] === 0) {
                                                Toastr.error(data['msg']);
                                            }
                                        },
                                    });
                                });
                            }
                            layer.close(index);
                        });
                    });
                    $('button[type="close"]').click(function () {
                        let index = parent.Layer.getFrameIndex(window.name);
                        parent.Layer.close(index);
                    });
                },
                screenShot: function (elementId, callback) {
                    var element = document.getElementById(elementId);
                    if (element === null) {
                        callback(null);
                        return;
                    }
                    Html2canvas(element,
                        {
                            useCORS: true,
                            scale: 1,
                            height: element.scrollHeight,
                            windowHeight: element.scrollHeight,
                        }).then(canvas => {
                        callback(canvas);
                    });
                },
            },
            preview: {
                bindPrintEvent: function () {
                    $('#ebill-print').click(function () {
                        Controller.api.preview.print();
                    });
                },
                print: function () {
                    var originalHtml = $('body', window.document).html();
                    var ebillContent = $('#ebill-content');
                    var ebillImageBase64 = ebillContent.css('backgroundImage').replace('url("', '').replace('")', '');
                    var ebillImage = document.createElement('img');
                    var ebillWidth = ebillContent.css('width');
                    var ebillHeight = ebillContent.css('height');
                    $(ebillImage).css('width', ebillWidth).css('height', ebillHeight).attr('src', ebillImageBase64).attr('id', 'ebill-image');
                    $('#ebill').html(ebillImage);
                    var printHtml = $('#ebill').html();
                    window.document.body.innerHTML = printHtml;
                    window.print();
                    //还原
                    window.document.body.innerHTML = originalHtml;
                    Controller.api.preview.bindPrintEvent();
                },
            },
            check: {
                bindEvent: function () {
                    //上传成功回调
                    $('#faupload-file').data('upload-success', function () {
                        var index = Layer.load();
                        var file = $('input[name="row[file]"]').val();
                        $.ajax({
                            type: "post",
                            url: location.href,
                            data: {'file': file},
                            success: function (data) {
                                if (data['code'] === 1) {
                                    Controller.api.check.showInfo(data['signature']);
                                } else if (data['code'] === 0) {
                                    Controller.api.check.showError();
                                }
                                $('.empty-hint').addClass('hidden');
                            },
                        });
                        Layer.close(index);
                    });
                },
                showInfo: function (signature){
                    $('.success','.result').remove();
                    $('.error').addClass('hidden');
                    var html = Template('successTpl', {info: signature});
                    $('.result').append(html);
                    var stamp = $('.stamp','.success');
                    stamp.load(function (){
                        var stampWidth = stamp.width();
                        var stampHeight = stamp.height();
                        stamp.css({
                            opacity : "0",
                            width : stampWidth * 2 + "px",
                            height : stampHeight * 2 + "px"
                        }).animate({
                            opacity : "1",
                            width : stampWidth + "px",
                            height : stampHeight + "px"
                        }, 200);
                    });
                    var src = $('#ebill-iframe').data('src');
                    $('#ebill-iframe').attr('src', src + '?action=detail' + '&bill=' + signature.bill + '&bill_id=' + signature.bill_id);
                    $('#ebill-content').removeClass('hidden');
                },
                showError: function (){
                    $('#ebill-content').addClass('hidden');
                    $('.success','.result').remove();
                    $('.error').removeClass('hidden');
                    var stamp = $('.stamp','.error');
                    var stampWidth = stamp.width();
                    var stampHeight = stamp.height();
                    stamp.css({
                        opacity : "0",
                        width : stampWidth * 2 + "px",
                        height : stampHeight * 2 + "px"
                    }).animate({
                        opacity : "1",
                        width : stampWidth + "px",
                        height : stampHeight + "px"
                    }, 200);
                }
            }
        }
    };
    return Controller;
});
